﻿<%-- 
    Copyright (C) Binod Nepal, Planet Earth Solutions Pvt. Ltd., Kathmandu.
	Released under the terms of the GNU General Public License, GPL, 
	as published by the Free Software Foundation, either version 3 
	of the License, or (at your option) any later version.
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
    See the License here <http://www.gnu.org/licenses/gpl-3.0.html>.
--%>

<%@ Page Title="I Can't Access My Account" Language="C#" MasterPageFile="~/Classifieds/Main.Master" AutoEventWireup="true"
    CodeBehind="CantAccessAccount.aspx.cs" Inherits="MixNP.Web.Classifieds.Account.CantAccessAccount" %>

<asp:Content ID="Content1" ContentPlaceHolderID="StyleSheetContentPlaceHolder" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ScriptsContentPlaceHolder" runat="server">
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="BodyContentPlaceHolder" runat="server">
    <asp:Panel ID="RecoveryPanel" runat="server" CssClass="bpad12">
        <h1>
            I Can't Access My Account</h1>
        <hr class="hr" />

        Please use this form to recovery your account using either of the recovery methods. We will send you
        account recovery instruction there.
        <h2>
            Preferred Recovery Method</h2>
        <asp:RadioButtonList ID="RecoveryMethodRadioButtonList" runat="server">
            <asp:ListItem Text="Send Me an SMS" Value="Send Me an SMS" Selected="True" />
            <asp:ListItem Text="Send Me an Email" Value="Send Me an Email" />
        </asp:RadioButtonList>
        <hr class="hr" />
        <h2>
            Please Type Your Email Address or Cell Number</h2>
        <asp:TextBox ID="RecoveryTextBox" runat="server" CssClass="textbox wide" />
        <br />
        We are monitoring requests from your IP Address
        <%= Pes.Utility.PageUtility.GetUserIPAddress() %>. Please make sure that you are entering a valid email
        or cell number.
        <asp:Literal ID="ErrorLiteral" runat="server" />
        <hr class="hr" />
        <input type="button" id="SaveButton" runat="server" value="Recovery My Account" onserverclick="SaveButton_Click" />
    </asp:Panel>
    <asp:Panel ID="ConfirmationPanel" runat="server" CssClass="bpad12" Visible="false">
        <h2>
            Recovery Instructions Sent
        </h2>

        <p>
            Recovery instruction was sent to <asp:Literal ID="RecoveryLiteral" runat="server" />.
        </p>

        <input type="button" id="Button1" runat="server" value="Return Back to the Home Page"
            onclick="top.location = '/';" />
    </asp:Panel>
</asp:Content>
<asp:Content ID="Content4" ContentPlaceHolderID="ScriptsContentPlaceHolderBottom"
    runat="server">
</asp:Content>
<script runat="server">
    public static Random random = new Random();

    protected void SaveButton_Click(object sender, EventArgs e)
    {
        bool email = (RecoveryMethodRadioButtonList.SelectedItem.Value.Equals("Send Me an Email"));
        string address = RecoveryTextBox.Text;

        if (email)
        {
            if (MixNP.BusinessLayer.Users.IsValidEmailAddress(address))
            {
                this.ProcessEmail(address);
            }
            else
            {
                DisplayWarning("Invalid email address.");
                Pes.Utility.PageUtility.InvalidPasswordAttempts(this.Page, 2);
            }
        }
        else
        {
            if (MixNP.BusinessLayer.Profiles.IsValidCellNumber(address))
            {
                this.ProcessText(address);
            }
            else
            {
                DisplayWarning("Invalid cell number.");
                Pes.Utility.PageUtility.InvalidPasswordAttempts(this.Page, 2);
            }
        }



    }

    private void DisplayWarning(string message)
    {
        ErrorLiteral.Text = "<div class='alert vpad8'>" + message + "</div>";
    }

    private void ProcessEmail(string emailAddress)
    {
        string token = Guid.NewGuid().ToString();
        token = MixNP.BusinessLayer.Users.PasswordResetQueue(emailAddress, 'E', emailAddress, token);

        string url = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + "/recover/" + token + ".mix";
        url = string.Format("<a href='{0}' title='Reset Your Account on MixNP.com'>{0}</a>", url);

        string emailBody = System.IO.File.ReadAllText(this.Page.Server.MapPath("~/Classifieds/Templates/CantAccessAccount.htm"));
        emailBody = emailBody.Replace("{ConfirmationLink}", url);

        if (MixNP.BusinessLayer.Email.SendEmail("MixNP.User.Password.Reset", emailAddress, emailAddress, "Reset Your Password on MixNP.com", emailBody, "noreply@mixnp.com"))
        {
            RecoveryPanel.Visible = false;
            ConfirmationPanel.Visible = true;
            RecoveryLiteral.Text = emailAddress;
        }
    }

    private void ProcessText(string cellNumber)
    {
        string emailAddress = MixNP.BusinessLayer.Profiles.GetEmailAddress(cellNumber);
        string token = RandomString(6).ToUpper();
        token = MixNP.BusinessLayer.Users.PasswordResetQueue(emailAddress, 'T', cellNumber, token);

        string message = string.Format("Reset Code : {0}.{1}{1}Visit http://mixnp.com/recover/ to reset your account.", token, Environment.NewLine);
        if (MixNP.BusinessLayer.TextMessage.SendText("MixNP.User.Password.Reset", cellNumber, message))
        {
            RecoveryPanel.Visible = false;
            ConfirmationPanel.Visible = true;
            RecoveryLiteral.Text = cellNumber;        
        }
    }

    private static string RandomString(int Size)
    {
        string input = "abcdefghijklmnopqrstuvwxyz0123456789";
        var chars = Enumerable.Range(0, Size)
                               .Select(x => input[random.Next(0, input.Length)]);
        return new string(chars.ToArray());
    }
</script>
